<template>
  <div class="brand-box" v-show="isShow">
    <el-dialog width="600px" top="5%" :title="dialogTitle" v-model="dialogFormVisible" :draggable="true" @close="dialogClose">
      <el-form ref="dialogFormRef" :model="dialogForm" :rules="dialogFormRules">
        <el-row>
          <el-col :span="12">
            <el-form-item prop="typeId" label="商品类型">
              <el-select style="width:90%" :disabled="isEdit" v-model="dialogForm.typeId" clearable @change="typeChange">
                <el-option v-for="item in typeOptions" :key="item.typeId" :label="item.typeName" :value="item.typeId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="categoryId" label="商品分类">
              <el-select style="width:90%" v-model="dialogForm.categoryId" clearable no-data-text="请先选择商品类型">
                <el-option v-for="item in simpleOptions" :key="item.categoryId" :label="item.categoryName"
                  :value="item.categoryId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="brandName" label="品牌名称">
              <el-input style="width:90%" v-model="dialogForm.brandName" placeholder="请输入品牌名称" @keypress.enter="submitHandle" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="tag" label="标签">
              <el-select style="width:90%" v-model="dialogForm.tag" filterable allow-create clearable>
                <el-option v-for="item in tagOptions" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="showPower" label="权重">
              <el-input style="width:90%" v-model="dialogForm.showPower" type="number" max="999999" maxlength="6"
                placeholder="请输入权重" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-loading="loading">
          <el-col :span="12">
            <el-form-item style="margin-bottom:0;" prop="logoImg" label="品牌logo">
              <div v-show="!dialogForm.logoImg" class="upload-box-div" @click="uploadImg(1)">
                <el-icon style="margin:auto;" size="24">
                  <Plus />
                </el-icon>
              </div>
              <div class="upload-box" v-show="dialogForm.logoImg">
                <img :src="dialogForm.logoImg" alt="">
                <el-icon color="#ffffff" class="upload-close" @click="removeImg(1)">
                  <Close />
                </el-icon>
              </div>
            </el-form-item>
            <el-button style="margin:5px 0;" type="primary" @click="toSucai('logoImg')" size="small">从素材库选择</el-button>
            <div style="width:50%">
              <small>提示：
                logo图片建议长宽比为1:1
                图片格式为png或jpg</small>
            </div>
          </el-col>
          <el-col :span="12">
            <el-form-item style="margin-bottom:0;" prop="headImg" label="品牌宣传图">
              <div v-show="!dialogForm.headImg" class="upload-box-div" @click="uploadImg(2)">
                <el-icon style="margin:auto;" size="24">
                  <Plus />
                </el-icon>
              </div>
              <div class="upload-box" v-show="dialogForm.headImg">
                <img :src="dialogForm.headImg" alt="">
                <el-icon color="#ffffff" class="upload-close" @click="removeImg(2)">
                  <Close />
                </el-icon>
              </div>
            </el-form-item>
            <el-button style="margin:5px 0;" type="primary" @click="toSucai('headImg')" size="small">从素材库选择</el-button>
            <div style="width:50%">
              <small>提示：
                品牌宣传图片分辨率为1080*435
                图片格式为png或jpg</small>
            </div>
          </el-col>
        </el-row>
        <el-divider v-if="dialogForm.typeId == 2" border-style="dashed" />
        <el-row v-if="dialogForm.typeId == 2">
          <el-col :span="12">
            <el-form-item style="margin-bottom:0;" prop="rechargeTypeList" label="充值类型">
              <div class="czlx-box">
                <div class="w-f-c" v-for="(item,index) in dialogForm.rechargeTypeList" :key="item">
                  <el-input style="width:90%" v-model="item.rechargeTypeName" placeholder="请输入充值类型" />
                  <el-icon size="20" @click="deleteRecharge(dialogForm.rechargeTypeList,index)">
                    <CircleClose />
                  </el-icon>
                </div>
                <el-link style="width: fit-content;" type="primary" @click="addRecharge">新增充值类型</el-link>
              </div>
              <!-- <el-select v-model="dialogForm.rechargeTypeList" readonly multiple placeholder="请选择充值类型" @click="rechargeClick"
                @change="rechargeChange">
                <el-option v-for="item in rechargeTypeOptions" :key="item.rechargeTypeId" :label="item.rechargeTypeName"
                  :value="item.rechargeTypeId" />
              </el-select> -->
            </el-form-item>
          </el-col>
          <!-- <el-divider border-style="dashed" /> -->
        </el-row>
        <!-- <el-row>
          <el-col :span="24">
            <el-form-item prop="produceMode" label="生产方式">
              <el-radio-group :disabled="isEdit" v-model="dialogForm.produceMode">
                <el-radio :label="1">自动生产</el-radio>
                <el-radio :label="2">手动生产</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="dialogForm.produceMode == 1" prop="recordId" label="">
              <el-select :disabled="isEdit" style="width:50%" v-model="dialogForm.recordId" clearable placeholder="请选择一个生产接口">
                <el-option v-for="item in apiOptions" :key="item.recordId" :label="item.recordName" :value="item.recordId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row> -->
        <!-- <el-form-item prop="password" label="登录密码">
          <el-input v-model="dialogForm.password" type="password" show-password placeholder="请输入管理员登录密码"
            @keypress.enter="submitHandle" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitHandle">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
  <input ref="uploadInputRef" style="display:none" type="file" accept="image/*" @change="uploadChange">
  <choose-file ref="chooseFileRef" @dialogClose="chooseFileClose" />
</template>

<script>
import { reactive, ref, toRefs } from 'vue'
import axios from "axios"
import api from '../api'
import { warningDeal } from '@/utils/utils'
import hexMD5 from "@/utils/md5.min.js"
import chooseFile from '@/components/chooseFile.vue'
export default {
  components: {
    chooseFile,
  },
  setup(props, context) {
    const dialogFormRef = ref(null)
    const uploadInputRef = ref(null)
    const chooseFileRef = ref(null)

    const imgUrlPass = (rule, value, callback) => {
      if (!state.dialogForm.logoImg) {
        callback(new Error('请上传品牌logo'))
      } else {
        callback()
      }
    }

    const passRecharge = (rule, value, callback) => {
      let is = true
      value && value.map(item => {
        if (!item.rechargeTypeName) {
          is = false
        }
      })
      if (is) {
        callback()
      } else {
        callback(new Error('请输入充值类型'))
      }
    }

    const state = reactive({
      fileProp: null,
      isShow: true,
      isImg: null,
      loading: false,
      isEdit: false,
      dialogTitle: '',
      dialogFormVisible: false,
      dialogForm: {},
      fileForm: {},
      dialogFormRules: {
        typeId: [
          { required: true, message: '请选择商品类型', trigger: 'blur' },
        ],
        categoryId: [
          { required: true, message: '请选择商品分类', trigger: 'blur' },
        ],
        brandName: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' },
        ],
        logoImg: [
          { required: true, validator: imgUrlPass, trigger: 'blur' },
        ],
        // produceMode: [
        //   { required: true, message: '请选择生产方式', trigger: 'blur' },
        // ],
        // recordId: [
        //   { required: true, message: '请选择生产接口', trigger: 'blur' },
        // ],
        password: [
          { required: true, message: '请输入管理员登录密码', trigger: 'blur' },
        ],
        rechargeTypeList: [
          { required: true, validator: passRecharge, trigger: 'blur' },
        ],
      },
      typeOptions: [],
      simpleOptions: [],
      apiOptions: [],
      rechargeTypeOptions: [],
      tagOptions: [],
    })

    function getTagOptions() {
      const obj = {
        type: 1,
      }
      api.goodsTagList(obj).then(res => {
        if (res.code == '200') {
          state.tagOptions = res.data.tagList
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function getRecharge(brandId) {
      const obj = {
        brandId
      }
      api.goodsInfoRechargeType(obj).then(res => {
        if (res.code == '200') {
          state.rechargeTypeOptions = res.data
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function getTypeOptions() {
      api.goodsTypeListSimple().then(res => {
        if (res.code == '200') {
          state.typeOptions = res.data
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }
    function getFlOptions(typeId) {
      api.goodsCategoryListSimple({ typeId }).then(res => {
        if (res.code == '200') {
          state.simpleOptions = res.data
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function getRechargeType(list) {
      const myArr = []
      list && list.map(item => {
        myArr.push(item.rechargeTypeId)
      })
      return myArr
    }

    function dialogShow(data) {
      state.isShow = true
      state.dialogTitle = data ? '编辑商品品牌' : '新增商品品牌'
      state.isEdit = data ? true : false
      state.dialogForm = { ...data } || {}
      state.dialogFormVisible = true
      state.dialogForm.rechargeTypeList = []
      getTypeOptions()
      getTagOptions()
      if (data) {
        state.dialogForm.rechargeTypeList = data.brandRechargeTypes && [...data.brandRechargeTypes]
        getFlOptions(data.typeId)
        getRecharge(data.brandId)
        return
      }
    }

    function dialogClose() {
      dialogFormRef.value.resetFields()
    }

    function typeChange(e) {
      state.dialogForm.categoryId = null
      if (!e) {
        state.simpleOptions = []
        return
      }
      getFlOptions(e)
    }

    function uploadImg(i) {
      if (state.loading) return
      state.isImg = i
      uploadInputRef.value.click()
    }

    //上传文件
    async function uploadChange(e) {
      state.loading = true
      let fileForm = {}
      fileForm.file = e.target.files[0]
      fileForm.fileName = e.target.files[0].name
      await uploadFile(fileForm)
      uploadInputRef.value.value = ''
    }

    async function uploadFile(fileForm) {
      let param = new FormData()
      param.append('file', fileForm.file, fileForm.fileName)
      let config = {
        headers: {
          'Content-Type': 'multipart/form-data',
          token: '',
          Authorization: `'','','',3,20,''`,
          platformHeadType: 'ilinkPlatform',
        }
      }
      let url = '/ums/file/upload/img'
      if (PROCESS_ENV.ENVIRONMENT == 'Production') {
        url = '/coupon_h5' + url
      }
      await axios.post(url, param, config).then(res => {
        if (res.data.code == '200') {
          if (state.isImg == 1) {
            state.dialogForm.logoImg = res.data.data.ossUrl
          } else if (state.isImg == 2) {
            state.dialogForm.headImg = res.data.data.ossUrl
          }
        } else {
          warningDeal(res.data.msg)
        }
        state.loading = false
      }).catch(err => {
        console.log(err)
        state.loading = false
      })
    }

    function removeImg(i) {
      if (i == 1) {
        state.dialogForm.logoImg = null
      } else if (i == 2) {
        state.dialogForm.headImg = null
      }
    }

    function submitHandle() {
      getRechargeTypeList(state.dialogForm.rechargeTypeList)
      if (state.loading) return
      dialogFormRef.value.validate((valid, fields) => {
        if (valid) {
          if (state.dialogForm.brandId) {
            editBrand()
          } else {
            addBrand()
          }
        }
      })
    }

    function getreName(rechargeTypeId) {
      let name = ''
      state.rechargeTypeOptions && state.rechargeTypeOptions.map(item => {
        if (item.rechargeTypeId == rechargeTypeId) {
          name = item.rechargeTypeName
        }
      })
      return name
    }

    function getRechargeTypeList(list) {
      return list
      const myArr = []
      const reArr = []
      state.rechargeTypeOptions && state.rechargeTypeOptions.map(item => {
        reArr.push(item.rechargeTypeId)
      })
      list && list.map(item => {
        if (reArr.length > 0) {
          if (reArr.includes(item)) {
            myArr.push({
              rechargeTypeId: item,
              rechargeTypeName: getreName(item),
            })
          } else {
            myArr.push({
              rechargeTypeId: null,
              rechargeTypeName: item,
            })
          }
        } else {
          myArr.push({
            rechargeTypeId: null,
            rechargeTypeName: item,
          })
        }
      })
      console.log(myArr)
      return myArr
    }

    function addBrand() {
      const obj = {
        brandName: state.dialogForm.brandName || null,
        categoryId: state.dialogForm.categoryId || null,
        typeId: state.dialogForm.typeId || null,
        logoImg: state.dialogForm.logoImg || null,
        headImg: state.dialogForm.headImg || null,
        tag: state.dialogForm.tag || null,
        showPower: state.dialogForm?.showPower || null,
        // produceMode: state.dialogForm.produceMode || null,
        // recordId: state.dialogForm.recordId || null,
        rechargeTypeList: getRechargeTypeList(state.dialogForm.rechargeTypeList),
        // password: hexMD5(state.dialogForm.password),
      }
      api.goodsBrandAdd(obj).then(res => {
        if (res.code == '200') {
          context.emit('dialogClose')
          state.dialogFormVisible = false
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function editBrand() {
      const obj = {
        brandId: state.dialogForm.brandId,
        brandName: state.dialogForm.brandName || null,
        categoryId: state.dialogForm.categoryId || null,
        typeId: state.dialogForm.typeId || null,
        logoImg: state.dialogForm.logoImg || null,
        headImg: state.dialogForm.headImg || null,
        tag: state.dialogForm.tag || null,
        showPower: state.dialogForm?.showPower || null,
        // produceMode: state.dialogForm.produceMode || null,
        // recordId: state.dialogForm.recordId || null,
        rechargeTypeList: getRechargeTypeList(state.dialogForm.rechargeTypeList),
        // password: hexMD5(state.dialogForm.password),
      }
      api.goodsBrandModify(obj).then(res => {
        if (res.code == '200') {
          context.emit('dialogClose')
          state.dialogFormVisible = false
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function rechargeChange(e) {
      console.log(e)
    }

    function deleteRecharge(list, index) {
      list && list.splice(index, 1)
    }

    function addRecharge() {
      state.dialogForm.rechargeTypeList.push({
        rechargeTypeId: null,
        rechargeTypeName: null
      })
    }

    function toSucai(name) {
      state.fileProp = name
      chooseFileRef.value.dialogShow()
    }

    function chooseFileClose(file) {
      state.dialogForm[state.fileProp] = file.filePath
    }

    return {
      ...toRefs(state),
      chooseFileRef,
      dialogFormRef,
      uploadInputRef,
      dialogShow,
      dialogClose,
      typeChange,
      uploadChange,
      uploadImg,
      removeImg,
      submitHandle,
      rechargeChange,
      deleteRecharge,
      addRecharge,
      toSucai,
      chooseFileClose,
    }
  }
}
</script>

<style lang="scss" scoped>
.upload-box {
  position: relative;
  > img {
    max-width: 150px;
    max-height: 80px;
  }
  .upload-close {
    position: absolute;
    right: 0;
    top: 0;
    cursor: pointer;
    background-color: rgba($color: #000000, $alpha: 0.5);
  }
}
.upload-box-div {
  width: 80px;
  height: 80px;
  border: 1px dashed #a5a5a5;
  display: flex;
  cursor: pointer;
}
.czlx-box {
  display: flex;
  flex-flow: column;
  gap: 5px;
}

.w-f-c {
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
}
</style>